package com.jvm.interpreter.instruction;

import com.jvm.Utils;
import com.jvm.classfile.model.Class;
import com.jvm.classfile.model.CpInfo;
import com.jvm.classfile.model.Instance;
import com.jvm.interpreter.Frame;
import com.jvm.interpreter.Instruction;
import com.jvm.interpreter.MetaSpace;

/**
 * @program: diy_simple_jvm
 * @description: new指令
 * @author: CaoYong
 * @create: 2021-07-09 15:49
 **/
public class NewInst implements Instruction {

    String className;

    public NewInst(String className) {
        this.className = className;
    }

    @Override
    public int offset() {
        return 3;
    }

    @Override
    public void eval(Frame frame) {
        Class clazz = MetaSpace.getClassLoader().findClass(this.className);
        Utils.clinit(clazz);

        Instance instance = clazz.newInstance();
        frame.pushRef(instance);

        frame.pc += offset();
    }

    static NewInst parse(java.io.DataInputStream dis, CpInfo[] cp) throws java.io.IOException {
        return new NewInst(Utils.getClassName(cp, dis.readUnsignedShort()));
    }
}
